/*
 The MIT License
 
 Copyright InScopeApps{+} 2009.
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

#import "inscp_finder.h"

#define kAppId          @"com.apple.finder"
#define kNoFinderWindow @"No finder window found."

@implementation inscp_finder

@synthesize finder;

- (id)init{
    self = [super init];
	if(self){
        self.finder = [SBApplication applicationWithBundleIdentifier:kAppId];
    }
    return self;
}

- (NSString *)frontMostFinderURL{
    //the front window looks like it is always the first in the array
    //if this is not the case we will need to loop over the windows
    //and inspect their indices, the windows count from front to back
    @try{
        finderWindow *frontWindow = [[finder windows] objectAtIndex:0];
        finderFolder *folder = [[frontWindow properties] objectForKey:@"target"];
        return [folder URL];
    }
    @catch(id theException){
        NSLog(kNoFinderWindow);
    }
    
    return nil;
}

- (inscp_paths *)getSelectedFinderItems{
    finderItem *eachItem;
    inscp_paths *selected = [[inscp_paths alloc] init];
    
    //get selected finder items
    @try{
        for(eachItem in [[finder selection] get]){
            [selected addPath:[eachItem URL]];
        }
    }
    @catch(id theException){
        NSLog(kNoFinderWindow);
    }
    
    //if nothing is selected, try to get the 
    //directory of the front most finder window
    if([selected count] == 0){
        [selected addPath:[self frontMostFinderURL]];
    }
    
    [selected autorelease];
    return selected;
}

- (void)dealloc{
	[finder release];
    
	[super dealloc];
}

@end
